import 'package:flutter/material.dart';
import 'package:hi_base/view_util.dart';

// 可动态改变位置的Header组件
// 性能优化：局部刷新应用@刷新原理 : 让局部刷新，不要全局刷新
class HiFlexibleHeader extends StatefulWidget {
  final String name; // 名称
  final String face; // 图像
  final ScrollController controller;

  const HiFlexibleHeader(
      {super.key,
      required this.name,
      required this.face,
      required this.controller});

  @override
  State<HiFlexibleHeader> createState() => _HiFlexibleHeaderState();
}

class _HiFlexibleHeaderState extends State<HiFlexibleHeader> {
  // static const double MAX_BOTTOM = 30;
  static const double MAX_BOTTOM = 35;
  static const double MIN_BOTTOM = 10;

  //滚动范围
  static const MAX_OFFSET = 80;
  double _dyBottom = MAX_BOTTOM;

  @override
  void initState() {
    super.initState();
    widget.controller.addListener(() {
      var offset = widget.controller.offset;
      print('offset 顶部Heade 向上滑动的距离：:$offset'); // 从0 到 194
      // 算出padding 的变化:0-1
      var dyOffset = (MAX_OFFSET - offset) / MAX_OFFSET; // 值从1 到 -1.4 【值不确定的】
      print('dyOffset:$dyOffset');

      //根据dyOffset 算出具体的变化的padding值
      var dy = dyOffset * (MAX_BOTTOM - MIN_BOTTOM); // dy 值：20【最大值到最小值】 -  负值
      print('dy==>:$dy');
      //临界值保护:
      if (dy > (MAX_BOTTOM - MIN_BOTTOM)) {
        dy = MAX_BOTTOM - MIN_BOTTOM;
      } else if (dy < 0) {
        dy = 0;
      }
      print('dy==> ===》:$dy');

      setState(() {
        //算出实际的padding 值
        _dyBottom = MIN_BOTTOM + dy;
      });
      print('dy:$dy  _dyBottom:$_dyBottom');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.bottomLeft,
      //padding: EdgeInsets.only(bottom: 30, left: 10),
      padding: EdgeInsets.only(
          bottom: _dyBottom, left: 10), //核心内容：_dyBottom 动态变更，实现 padding 动态设置变更
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(23),
            child: cachedImage(widget.face, width: 46, height: 46),
          ),
          hiSpace(width: 8),
          Text(widget.name,
              style: TextStyle(fontSize: 11, color: Colors.black54))
        ],
      ),
    );
  }
}
